<template>
  <div class="comment">
    <h4 class="commInfo">发表评论</h4>
    <div class="commInp">
        <!-- 输入评论组件 -->
       <van-field v-model="commentMessage" rows="3" autosize type="textarea" placeholder="请输入留言" />
       <!-- 提交评论按钮 -->
       <van-button type="info" size="large" class="commentBtn" block @click="setComment">发表评论</van-button>
    </div>
    <!-- 评论信息展示区域 -->
    <div class="comments" v-for="(item, index) in commentList" :key="item.id">
       <div class="commHead">
         <span>第{{index + 1}}楼</span>
         <span>用户：{{item.user_name}}</span>
         <span>发表时间： {{item.add_time.substr(0, 10)}}</span>
       </div>
       <div class="commBody">
         <p>{{item.content}}</p>
       </div>
    </div>
    <!-- 加载更多按钮 -->
    <van-button plain size="large" block color="#F1354A" class="getmore" @click="getMoreComment">加载更多</van-button>

  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取评论列表数据
      commentList: [],
      // 评论数据分页
      pageIndex: 1,
      commentMessage: '',
      // 评论人处于第几层楼
      floor: 0
    }
  },
  created () {
    this.getCommentList()
  },
  methods: {
    async getCommentList () {
      // 获取资讯的ID
      // console.log(this.$route.params.id);
      const { data: res } = await this.$http.get(`/api/getcomments/${this.$route.params.id}?pageindex=${this.pageIndex}`)
      // console.log(res)
      // 获取数据失败
      if (res.status === 1) return this.$notify({ type: 'danger', message: '获取评论数据失败' })
      // 获取数据成功
      this.commentList = this.commentList.concat(res.message)
      // console.log(this.commentList)
    },

    // 监听点击加载更多按钮
    getMoreComment () {
      // 页数+1
      this.pageIndex++
      this.getCommentList()
    },

    // 监听发表评论按钮
    async setComment () {
      if (this.commentMessage.trim().length === 0) {
        return this.$notify({ type: 'danger', message: '留言不能为空' })
      }
      const { data: res } = await this.$http.post('/api/postcomment/' + this.$route.params.id, `content = ${this.commentMessage.trim()}`)
      console.log(res)
      // 提交评论信息失败
      if (res.status === 1) return this.$notify({ type: 'danger', message: '提交评论失败' })
      // 提交评论成功
      this.$notify({ type: 'success', message: '提交评论成功' })
      this.getCommentList()
      this.commentMessage = ''
      this.commentList = []
    }
  }
}
</script>

<style lang="less" scoped>
.comment {
  padding: 0 10px;
}

// 发表评论提示的题目样式
.commInfo {
  display: block;
  margin: 30px 0 20px 0;
  font-weight: bold;
  font-size: 18px;
}

// 输入评论区样式
.commInp {
  border-top: 1px solid #ccc;
  padding-top: 10px;
}

// 输入文本框样式
.van-field {
    border: 1px solid #ccc;
}

// 发表评论按钮样式
.commentBtn {
   margin: 6px 0;
}

// 评论信息
.comments {
  font-size: 12px;
  p {
    text-indent: 2em;
    margin: 0;
  }
  .commHead {
    height: 30px;
    background-color: #eee;
    line-height: 30px;
  }
  .commBody {
    line-height: 35px;
  }
}

// 加载更改按钮
.getmore {
  margin-top: 20px;
}
</style>
